import com.study.reflect_study.Food;
import org.junit.Test;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @author liuguibin
 * @date 2020-12-27 14:37
 * 调用类的私有属性，方法
 */
public class ReflectTest2 {
    @Test
    public void getResult() throws NoSuchFieldException, NoSuchMethodException, InvocationTargetException, IllegalAccessException, ClassNotFoundException, InstantiationException {
        /**
         *   Class.forName("com.study.reflect_study.Food");
         */
        Class<?> clazz = Class.forName("com.study.reflect_study.Food");
        //获取主类 Food
        Object obj = clazz.newInstance();//com.study.reflect_study.Food@22927a81

        /**
         * 私有属性
         */
        Field fruit1 = clazz.getDeclaredField("fruit1");
        //禁止Field的访问控制检查
        fruit1.setAccessible(true);
        //获取私有常量
        Object obj2 = fruit1.get(obj);//香蕉🍌！
        //获取私有常量，并赋值

        fruit1.set(obj, "梨");
        Object obj3 = fruit1.get(obj);//梨

        /**
         * 私有方法
         */
        Method getPri = clazz.getDeclaredMethod("getPri", String.class);//private void com.study.reflect_study.Food.getPri(java.lang.String)
        ////禁止Field的访问控制检查
        getPri.setAccessible(true);
        getPri.invoke(obj, "aa");//我是私有方法aa


    }
}
